package com.example.musicdemo1.ui.recommend

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.viewpager2.widget.ViewPager2
import com.example.musicdemo1.R
import com.example.musicdemo1.adapter.BannerAdapter
import com.example.musicdemo1.adapter.RecommendMusicAdapter
import com.example.musicdemo1.api.MusicApi
import com.example.musicdemo1.model.Banner
import com.example.musicdemo1.model.Music
import kotlinx.coroutines.launch
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class RecommendFragment : Fragment() {
    private val TAG = "RecommendFragment"
    private lateinit var bannerViewPager: ViewPager2
    private val handler = Handler(Looper.getMainLooper())
    private val bannerRunnable = object : Runnable {
        override fun run() {
            if (!::bannerViewPager.isInitialized) return
            bannerViewPager.currentItem = (bannerViewPager.currentItem + 1) % (bannerViewPager.adapter?.itemCount ?: 1)
            handler.postDelayed(this, 3000)
        }
    }

    private val api by lazy {
        val logging = HttpLoggingInterceptor().apply {
            level = HttpLoggingInterceptor.Level.BODY
        }
        
        val client = OkHttpClient.Builder()
            .addInterceptor(logging)
            .build()

        Retrofit.Builder()
            .baseUrl("http://121.37.40.55:3000/")
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(MusicApi::class.java)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_recommend, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupViews(view)
        loadData()
    }

    private fun setupViews(view: View) {
        bannerViewPager = view.findViewById(R.id.bannerViewPager)
        view.findViewById<androidx.recyclerview.widget.RecyclerView>(R.id.recommendRecyclerView).apply {
            layoutManager = GridLayoutManager(requireContext(), 3)
        }
    }

    private fun loadData() {
        lifecycleScope.launch {
            try {
                Log.d(TAG, "开始加载轮播图数据")
                val bannerResponse = api.getBanners()
                Log.d(TAG, "轮播图数据: $bannerResponse")
                
                val banners = bannerResponse.map { response ->
                    Banner(response.id, response.bannerImgUrl, "")
                }
                setupBanner(banners)

                Log.d(TAG, "开始加载推荐歌曲数据")
                val recommendResponse = api.getRecommends()
                Log.d(TAG, "推荐歌曲数据: $recommendResponse")
                
                val recommendations = recommendResponse.map { response ->
                    Music(response.id, response.name, "", response.recImgUrl)
                }
                setupRecommendList(recommendations)
            } catch (e: Exception) {
                Log.e(TAG, "加载数据失败", e)
                e.printStackTrace()
            }
        }
    }

    private fun setupBanner(banners: List<Banner>) {
        Log.d(TAG, "设置轮播图: ${banners.size} 个项目")
        bannerViewPager.adapter = BannerAdapter(banners)
        handler.postDelayed(bannerRunnable, 3000)
    }

    private fun setupRecommendList(musicList: List<Music>) {
        Log.d(TAG, "设置推荐列表: ${musicList.size} 个项目")
        view?.findViewById<androidx.recyclerview.widget.RecyclerView>(R.id.recommendRecyclerView)?.adapter = 
            RecommendMusicAdapter(musicList)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        handler.removeCallbacks(bannerRunnable)
    }
} 